package com.example.wm.controller;

import cn.hutool.db.Entity;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import com.example.wm.entity.*;
import com.example.wm.mapper.EmployedManageMapper;
import com.example.wm.service.EmployedManageService;

import com.example.wm.service.GetAceesstokenService;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController
//员工管理
@RequestMapping("/employedManage")
@CrossOrigin
public class EmployedContoller {
    @Resource
    private EmployedManageService employedManageService;
    @Resource
    private EmployedManageMapper employedManageMapper;
    @Resource
    private GetAceesstokenService getAceesstokenService;
    @Value("${smbm.appsecret}")
    private String appsecreted;
    @Value("${smbm.appId}")
    private String appid;

    @PostMapping("/getmassge")
// 需要在目标方法上添加@Transactional注解，将事务交给spring管理
    //获取手机号登录接口
    @Transactional
    public Result getmassge(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        String code = jsonObject.getString("code");
        String result = null;
        String access_token = null;


        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //响应模型
        CloseableHttpResponse res = null;
        String accessUrl = "https://api.weixin.qq.com/cgi-bin/token?appid=wxba6a21693d6b5a99&secret=836e5643d37955fbaa32894a8614c60e&grant_type=client_credential";

        //创建get请求
        HttpGet httpGet = new HttpGet(accessUrl);
        try {
            res = httpClient.execute(httpGet);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //获取响应实体
        HttpEntity responseEntity = res.getEntity();
        String resultDemo = null;
        try {
            resultDemo = EntityUtils.toString(responseEntity);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //转换成对象，好把需要的字段对应的值拿出来
        JSONObject json = JSONObject.parseObject(resultDemo);
        System.out.println(json);

        access_token = json.getString("access_token");
//        Wxaccesstken k=new Wxaccesstken();
//        k.setId(1);
//        k.set名称("八闽管家微信小程序");
//        k.setToken(access_token);
//        getAceesstokenService.updateById(k);
        List<EmployeeManagement> list = null;
        try {

            // 接口调用凭证：accessToken
            String baseUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
            HashMap<String, Object> requestParam = new HashMap<>();
            // 手机号调用凭证
            requestParam.put("code", code);
            // 发送post请求读取调用微信接口获取openid用户唯一标识
            String jsonStr = JSONUtil.toJsonStr(requestParam);
            HttpResponse response = HttpRequest.post(baseUrl)
                    .header(Header.CONTENT_ENCODING, "UTF-8")
                    // 发送json数据需要设置contentType
                    .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .body(jsonStr)
                    .execute();
             if (response.getStatus() == HttpStatus.HTTP_OK) {
                result = response.body();
                System.out.println(result);
                // 将获取到的手机号信息解析为 JSON 对象
                JSONObject jsons = JSONObject.parseObject(result);
                // 获取手机号码
                String phoneNumber = jsons.getJSONObject("phone_info").getString("phoneNumber");
                LambdaQueryWrapper<EmployeeManagement> lambdaQuery = new LambdaQueryWrapper<>();
                lambdaQuery.eq(EmployeeManagement::getPhonenumber, phoneNumber);
//                 employedManageService.getOne(lambdaQuery);
                list = employedManageMapper.selectList(lambdaQuery);
                 System.out.println(list);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultData.success("查询成功", list);

    }


//账号密码登入
    @PostMapping("/loginpass_name")
    public Result<Object> loginpass_name(@RequestBody EmployeeManagement employeeManagement){
//        String name=jsonObject.getString("name");
//        String password=jsonObject.getString("password");
//        System.out.println(name);
//        if(name==""){
//            return null;
//        }
        System.out.println("----------146");
        System.out.println(employeeManagement);
          LambdaQueryWrapper<EmployeeManagement> lq=new LambdaQueryWrapper<>();
          lq.eq(EmployeeManagement::getLoginname,employeeManagement.getLoginname());
          lq.eq(EmployeeManagement::getPaasswords,employeeManagement.getPaasswords());
        EmployeeManagement loginone= employedManageService.getOne(lq);
          Long n=employedManageService.count(lq);
          if(n==0){
              return null;
          }
        return ResultData.success(loginone);
    }

//修改报销相关信息

    @Transactional
    @PostMapping("/update")
    public Result update(@RequestBody EmployeeManagement employeeManagement){
        employedManageService.updateById(employeeManagement);
        return ResultData.success("操作成功");
    }
    @Transactional
    @PostMapping("/getbyid")

    public Result getById(@RequestBody JSONObject jsonObject){

        EmployeeManagement list=   employedManageMapper.selectById(jsonObject.getString("id"));

        return ResultData.success("操作成功",list);
    }
    @Transactional
    @GetMapping("/getallname")
//报销获取全部人员信息
    public Result getallname(){

        List<EmployeeManagement> list=   employedManageService.list();
        ArrayList<String> alist=new ArrayList<>();
        for(EmployeeManagement l:list){

            alist.add(l.getLoginname());
        }

        return ResultData.success("操作成功",alist);
    }


// 根据名字找weixinopenid
@Transactional
@PostMapping("/findopenid")
public Result findopenidByname(@RequestBody JSONObject jsonObject){
  LambdaQueryWrapper<EmployeeManagement> lq=new LambdaQueryWrapper<>();
  lq.eq(EmployeeManagement::getLoginname,jsonObject.getString("name"));
    EmployeeManagement g= employedManageService.getOne(lq);
   String weixinopenid=  g.getWeixinopenid();
    return ResultData.success("操作成功",weixinopenid);
}

    @PostMapping("/page")
    @Transactional
    public Result page(@RequestBody JSONObject jsonObject) {

        Page<EmployeeManagement> pageInfo = new Page<>(jsonObject.getLong("page"),jsonObject.getLong("pageSize"));
        LambdaQueryWrapper<EmployeeManagement> lq=new LambdaQueryWrapper<>();
        Page<EmployeeManagement>  list=employedManageService.page(pageInfo,lq);
        return ResultData.success(pageInfo);
    }
//根据姓名找
@Transactional
@PostMapping("/findname")

public Result findname(@RequestBody JSONObject jsonObject){
LambdaQueryWrapper<EmployeeManagement> lq=new LambdaQueryWrapper<>();
lq.eq(EmployeeManagement::getLoginname,jsonObject.getString("name"));
    EmployeeManagement list=   employedManageMapper.selectOne(lq);

    return ResultData.success("操作成功",list);
}
}


